from annoying.decorators import render_to
from django.db.models import F
from django.http import Http404
from django.shortcuts import redirect, get_object_or_404
from django.contrib import messages

from core.extensions.decorators import login_required

from core.forms import ParticipationForm
from core.models import Event, User, Participation
from core.views.event.details import details
from core.views.event.strategies_calculation import get_current_sum_for_user, check_patrons


@login_required()
@render_to('event/participation.html')
def join(request, id):
    event = get_object_or_404(Event, id=id)
    strategy = event.strategy.id
    user = User.objects.get(id=request.session['user_id'])
    with_patron = False
    if user in event.participants.all() \
        or event.participants.count() == event.max_participants_count \
        or event.status != Event.Status.Scheduled:
        raise Http404()
    if request.method == 'POST':
        form = ParticipationForm(request.POST)
        if form.is_valid():
            investment = form.cleaned_data['investment']
            patron = form.cleaned_data['patron']
            Participation.objects.create(event=event, user=user, investment=investment, patron=patron)
            event.current_sum = F('current_sum') + investment
            event.current_sum_for_user = get_current_sum_for_user(id, strategy, investment, patron)
            event.save()
            messages.info(request, 'joined')
            return redirect(details, id)
    else:
        form = ParticipationForm()
        with_patron = check_patrons(strategy);
    return {'form': form, 'with_patron': with_patron}